package com.example.my.shop.mybatis.controller;

import com.example.my.shop.mybatis.entity.TbUser;
import com.example.my.shop.mybatis.service.TbUserService;
import com.example.my.shop.mybatis.service.impl.TbUserServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

 /**
  * @ProjectName:
  * @Package:        com.example.my.shop.mybatis.controller
  * @ClassName:      User_infoByIdController
  * @Description:    用户信息详情功能
  * @Author:         Mr.Vincent
  * @CreateDate:     2019/6/1 15:37
  * @Version:        1.0.0
  */
@WebServlet(value = "/infoById")
public class User_infoByIdController extends HttpServlet {

    /**
     * @Method:        service
     * @Description:    根据id查询用户信息详情，前台是用ajax的json格式来进行数据传输的，所以后台也要将查询出的对象转换成json格式来输出
     * @Param:         [req, resp]
     * @return:        void
     * @Author:        Mr.Vincent
     * @Date:          2019/6/1
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决json中文乱码
        resp.setContentType("text/json,charset=utf-8");

        //获取前台传递到后台的参数id
        String id = req.getParameter("id");
        TbUserService tbUserService = new TbUserServiceImpl();

        //根据id查询出tbUser
        TbUser tbUserJson = tbUserService.findById(Long.parseLong(id));

        //因为前台是用ajax的json格式来进行数据传输的，所以需要把查询出来的结果也转换为json的格式返回给前台
        ObjectMapper mapper = new ObjectMapper();

        //这里我们用jackson的jar包来，把查询出的对象转换成json字符串，来返回给前台
        String json = mapper.writeValueAsString(tbUserJson);

        //最后将结果输出给前台
        PrintWriter out = resp.getWriter();
        out.print(json);
        out.flush();
        out.close();
    }
}
